package com.sky.happygos.YiPush;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;


/**
 * Created by qqqqqqq on 2017/4/7.
 */

public class TcpClient extends Thread {

    Socket s;
    Handler handler;
    String host;
    int port;
    Proto heartP;
    String userid;

    DataInputStream input;
    DataOutputStream output;
    public String subkey;

    public boolean running = true;

    private Timer timer = new Timer();

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    OkHttpClient client;
    String httpUrl = "http://192.168.1.103:3333";


    public TcpClient(String host, int port, Handler hander){
        this.handler = hander;
        this.host = host;
        this.port = port;
    }
    public void setUserid(String userid){
        this.userid = userid;
    }

    public void initTcp(){
        try {
            s = new Socket(host,port);
            input = new DataInputStream(s.getInputStream());
            output = new DataOutputStream(s.getOutputStream());

            Proto auth = new Proto(Cmd.AUTH,userid,"AUTH");
            auth.writeSocket(output);

            Proto p = Proto.readSocket(input);
            subkey = p.data;
            Message connect = new Message();
            connect.arg1 = 666;
            handler.sendMessage(connect);
            Message message = new Message();
            message.obj = p;


            heartP = new Proto(Cmd.HEARTBEAT,subkey,"HEARTBEAT");
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    try {
                        heartP.writeSocket(output);
                    } catch (IOException e) {
                        e.printStackTrace();
                        return;
                    }
                    Log.v("HEARTBEAT","HEARTBEAT SEND");
                }
            };
            timer = new Timer();
            timer.schedule(task, 5*1000, 5*1000);

            while(running)
            {
                Proto reply = Proto.readSocket(input);
                if (reply.cmd == Cmd.MSG){
                    Message m = new Message();
                    m.obj = reply;
                    handler.sendMessage(m);
                }
                Log.v("reply :",reply.data);
            }

        }catch(Exception ex)
        {
            ex.printStackTrace();
            try {
                timer.cancel();
                sleep(5000);
                s.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                initTcp();
            }
        }
    }


    public String pushMessage(String msg, Callback callback) throws IOException {
        client = new OkHttpClient();
        return post(httpUrl+"/push",msg,callback);
    }

    public String getOnlineUser(Callback callback) throws IOException {
        client = new OkHttpClient();
        return get(httpUrl+"/online/user",null,callback);
    }



    public String pushMessageToRoom(String msg, Callback callback) throws IOException {
        return post(httpUrl+"/push/room",msg,callback);
    }
    private String post(final String url, String json, final Callback callback) throws IOException {
        if(client ==null){
            client = new OkHttpClient();
        }
        final RequestBody body = RequestBody.create(JSON, json);

        AsyncTask asyncTask = new AsyncTask<String,Integer,Boolean>() {
            @Override
            protected Boolean doInBackground(String... objects) {

                Request request = new Request.Builder()
                        .url(url)
                        .post(body)
                        .build();
                try {
                    client.newCall(request).execute();
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
                return true;
            }
        }.execute();

//
        return "success";
    }
    private String get(String url, String param, final Callback callback) throws IOException {
        if(client ==null){
            client = new OkHttpClient();
        }
        final String allUrl;
        if (param != null){
            allUrl = url+"?"+param;
        }else{
            allUrl = url;
        }

        AsyncTask asyncTask = new AsyncTask<String,Integer,Boolean>() {
            @Override
            protected Boolean doInBackground(String... objects) {

                Request request = new Request.Builder()
                            .url(allUrl)
                            .get()
                            .build();
                client.newCall(request).enqueue(callback);
                return true;
            }
        }.execute();

        return "success";
    }

    public boolean joinRoom(final String roomid){
        AsyncTask asyncTask = new AsyncTask<String,Integer,Boolean>() {
            @Override
            protected Boolean doInBackground(String... objects) {
                Proto proto = new Proto(Cmd.JOIN_ROOM,subkey,roomid);
                try {
                    proto.writeSocket(output);
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
                return true;
            }
        }.execute();
        return true;
    }

    public boolean leaveRoom(final String roomid){
        AsyncTask asyncTask = new AsyncTask<String,Integer,Boolean>() {
            @Override
            protected Boolean doInBackground(String... objects) {
                Proto proto = new Proto(Cmd.LEAVE_ROOM,subkey,roomid);
                try {
                    proto.writeSocket(output);
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
                return true;
            }
        }.execute();
        return true;
    }

//    public String getMsgs(Callback callback) throws IOException {
//        return getMsgs("",callback);
//    }

    public String getMsgs(String to, final String type, Callback callback) throws IOException {
        String parmas = "me="+to+"&mid="+0+"&userKey="+userid+"&type="+type;
        return get(httpUrl+"/getMsgs",parmas,callback);
    }

    @Override
    public void run() {
        initTcp();
    }
}
